<?php
class Narrower {
	
	private $limitingSQL; 	// This is used to get around the problem
								// of not knowing who is trying to access the data.
								// This can be 1 of three things:
								// 		CA: 		"caId='##'"
								//		Provider: 	"providerId='##'"
								//		State:		"1=1"
	private $table;			// This table is the one from where the data 
								// will be acquired.
	private $narrow_items = array();	// Associative array of narrow items
	private $method;		// GET or POST
	private $method_name;
	
	private $dateIds = array();
	
	/**
	We are just going to initialize the method here
	*/
	public function __construct ($type) {
		
		// Determining the input type so that queries can be made and 
		// the form can see daylight!
		if ($type == "GET")
			$this->method = &$_GET;
		else if ($type == "POST")
			$this->method = &$_POST;
			
		$this->method_name = $type;
			
		//$this->limitingSQL = $limitingSQL;
	}
	
	
	/**
	This function just checks all incoming variables to see if any are
	AJAX requests from the narrower form. If so, we don't want to render
	the rest of the HTML page. Instead, we just spit back what is required
	and exit the code.
	
	This simply calls genHTML on the narrow_item object with the "ajax" param
	*/
	public function ajax () {
		foreach($this->narrow_items as $key => $item) {
			if (count($item->parents) > 0) {		// If it has any parents, then chances are, there is some ajax code
				$tmpName = str_replace(" ", "_", $item->field_name);
				if ($this->method["load_narrower_$tmpName"]) {
					if ($this->method["narrower_{$item->parents[0]}"] == "0" && count($item->parents) == 1)
						echo $item->genHTML('all');
					else
						echo $item->genHTML("ajax");
					exit();
				}	// Posted for AJAX
			}	// Parent has some children!
		}	// 	/foreach
		
	}
	
	
	/**
	This is a very simple function whose sole purpose is to check if the 
	user has submitted a narrower form.
	*/
	public function posted () {
		return (isset($this->method['narrower_submit']));
	}
	
	
	/**
	This function goes through all of the narrow items and compiles a
	list which is turned into an appendix to the SQL query.
	*/
	public function process () {
		$global_valid = true;	// If this is false, then we aren't going to 
								// return anything to the user.	
		$sqlString = "";
		foreach ($this->narrow_items as $item) {
			if (!$item->validate())
				$global_valid = false;
			
			$sqlString .= $item->genSQL();
		}
		
		if (!$global_valid)
			return false;
		else
			return $sqlString;
	}
	
	
	/**
	This function adds different types of elements to the array 
	narrow_items. This function is to be called before create_form so that all the 
	form elements have been created in this object
	
	The name variable is needed to refer the form items again when it is time
	to assign dependents for ajax
	*/
	public function add_form_element($name, $type, $sql, $ajaxSQL, $tableName) {
		$type = split(":", $type);
		switch ($type[0]) {
		case "dates":
			$this->narrow_items[$name] = new DatesOnly($name, $this->method_name, $tableName);
			
			$tmpFieldName = str_replace(" ", "_", $name);
			array_push($this->dateIds, "narrower_".$tmpFieldName."_entry");
			array_push($this->dateIds, "narrower_".$tmpFieldName."_ending");
			break;
		case "number":
			$this->narrow_items[$name] = new NumberOnly($name, $this->method_name, $tableName);
			break;
		case "dropdown":
			$this->narrow_items[$name] = new DropDownMenu($name, $sql, $ajaxSQL, $this->method_name, $tableName);
			break;
		case "comma":
			$this->narrow_items[$name] = new CommaDropDown($name, $sql, $ajaxSQL, $this->method_name, $tableName);
			break;
		case "commafusion":
			$this->narrow_items[$name] = new CommaDropDownFusion($name, $sql, $ajaxSQL, $this->method_name, $tableName);
			break;
		}
	}
	
	
	/**
	This function adds the children as dependents to the parent so that they 
	get updated through Ajax whenever the parent changes
	
	It also adds the parents to the children
	*/
	public function tie ($parent, $child) {
		//echo ("TRYING TO ADD CHILD $child to PARENT $parent -- ".$this->narrow_items[$parent]->children);
		array_push($this->narrow_items[$parent]->children, $child);
		array_push($this->narrow_items[$child]->parents, $parent);
	}
	
	/**
	This function loops through all of the narrow_item elements and writes: 
	1) PHP/HTML for the actual form
	2) Javascript for the styling
	3) Javascript for the AJAX handling
		- for each item, 
			if it has children	// recursively for their children
				on change item, ajax chain children in sequence
	*/
	public function create_form () {
		// Javascript AJAX handling
		
		$jsAJAX = "";
		$jsAJAX .= "<script language='javascript' type='text/javascript'>";
		
		foreach ($this->narrow_items as $key => $item) {
			// Only add AJAX for elements with only 1 parent // no support for multiple parents
			// i.e., only add code here for elements with children and no parents
			
			
			// Test: Enabling function for elts with parents....
			if (count($item->children) != 0) {
				$numChildren = count($item->children);
				
				
				$itemName = str_replace(" ", "_", $item->field_name);
				$jsAJAX .= "function narrower_ajax_$itemName () {";
				
				foreach ($item->children as $child) {	// $child is simple an array of strings
					
					// NEED TO ADD SUPPORT FOR MULTIPLE PARENTS! SEE GROUP NAME!
					$childName = str_replace(" ", "_", $child);
					
					$dataString = "'load_narrower_$childName=1";
					foreach ($this->narrow_items[$child]->parents as $parent) {
						$parentName = str_replace(" ", "_", $parent);
						$dataString .= "&narrower_$parentName='+$('[name=narrower_$parentName]').val()+'";
					}
					
					$jsAJAX .= "$.ajax({
						method: 'get',
						url: '',
						data: $dataString',
						
						success: function (response) {
							$('#narrower_$childName').html(response);
							alert('changing #narrower_$childName');
							$('[name=narrower_$childName]').change();\n";				// Triggering change event for nesting parents and children
				}
				
				while ($numChildren > 0) {
					$jsAJAX .= "}});\n";
					$numChildren -= 1;
				}
				
				$jsAJAX .= "}\n\n";	// Closing function
			}
		}
		$jsAJAX .= "</script>";
		
		// Actual PHP/HTML form
		$phpForm = "<center><div id='narrower'><form method='{$this->method_name}' action=''><table><tr>\n";

		$itemNum = 1;
		$totalPerRow = 4;
		foreach ($this->narrow_items as $key => $item) {
			if ($itemNum > $totalPerRow) {
				$phpForm .= "</tr><tr>\n";
				$itemNum = 1;
			}
			$tmpKey = str_replace(" ", "_", $key);
			$phpForm .= "<td><div class='narrow_item'><strong>$key</strong><br /><div id='narrower_$tmpKey'>".$item->genHTML("regular")."</div></div></td>\n\n";
			$itemNum ++;
		}
		$phpForm .= "</tr></table><br /><br /><input type='submit' value='Submit form' name='narrower_submit' />\n".
				"</form></div>\n";
			
		$phpForm .= "<div id='narrower_toggle'>Hide above form</div></center>\n\n";
		
		// Javascript styling
		$jsStyle = "";
		
		$jsStyle .= "<script language='javascript' type='text/javascript'>\n".
					"$(window).ready(function () {\n".

					// Toggler
					"$('#narrower_toggle').css('width', '200px');\n".
					"$('#narrower_toggle').css('height', '20px');\n".
					"$('#narrower_toggle').css('background-color', '#3399FF');\n".
					"$('#narrower_toggle').css('border', 'thin solid black');\n".
					"$('#narrower_toggle').css('cursor', 'pointer');\n".
					"$('#narrower_toggle').text('Hide above form');\n".
					"$('#narrower_toggle').css('border-top', 'none');\n".

					"$('#narrower_toggle').mouseover( function () {\n".
						"$('#narrower_toggle').css('background-color', '#246BB3');\n".
					"});\n".
					
					"$('#narrower_toggle').mouseout( function () {\n".
						"$('#narrower_toggle').css('background-color', '#3399FF');\n".
					"});\n".
	
					"$('#narrower_toggle').click( function () {\n".
						"if ($('#narrower_toggle').text() == 'Hide above form') {\n".
							"$('#narrower_toggle').text('Show hidden form');\n".
							"$('#narrower').slideUp('slow');\n".
						"} else {\n".
							"$('#narrower_toggle').text('Hide above form');\n".
							"$('#narrower').slideDown('slow');\n".
						"}\n".
					"});\n".
	

					
					// Main form box
					"$('#narrower').css('background-color', '#3399FF');\n".
					"$('#narrower').css('width', '98%');\n".
					"$('#narrower').css('height', '325px');\n".
					"$('#narrower').css('overflow', 'auto');\n".

					// Individual form elements
					"$('.narrow_item').css('border', 'thin dotted black');\n".
					"$('.narrow_item').css('background-color', '#2B82D9');\n".
					//"$('.narrow_item').css('width', '200px');\n".
					"$('.narrow_item').css('float', 'left');\n".
					//"$('.narrow_item').css('margin', '10px');\n".
					"$('.narrow_item').css('padding', '10px');\n".
					"$('.narrower_error_message').css('font-size', '12px');\n".
					"$('.narrower_error_message').css('color', 'red');\n".
					"$('.narrower_error_message').css('font-weight', 'bold');\n".
					"$('.narrower_error_message').css('background-color', '#3399FF');\n";
					
					foreach ($this->dateIds as $name) {
						$jsStyle .= "$('#{$name}').datepicker();\n";
					}
					
					$jsStyle .= "});\n".

					"</script>\n";
	
	
		echo $jsAJAX;
		echo $phpForm;
		echo $jsStyle;
	
	}
}



///////////////////////////// THE FOLLOWING CLASSES ARE FOR THE FORM_ITEMS //////////
abstract class FormElement {
	private $error;			// A string that is changed at will.
	public $children = array();		// An array of strings which are key strings 
								// to the associative array in Narrower
	public $parents = array();		// Same as above except their parents.
	private $field_name;	// This will be used in generating the name of the form element
	private $tableName;	// This will be used in genSQL
	private $method;

	
	public function __construct ($field_name, $type) {
		$this->field_name = $field_name;
	}
	
	/*
	This function returns a string IF $method['someuniquename'] is valid
	
	The string is used to add onto the paramstring in narrower
	*/
	public function genSQL () {
		if ($this->validate()) {
			//...
		}
	}
	
	/*
	This validates the $method['someuniquename'] value and returns true or false
	*/
	abstract function validate();
	
	// Derived classes redefine this anyway
	abstract function  genHTML ($type);
}

abstract class TextElement extends FormElement {
}

class NumberOnly extends TextElement {
	public function __construct ($field_name, $type, $tableName) {
		$this->field_name = $field_name;
		if ($type == "GET")
			$this->method = &$_GET;
		else if ($type == "POST")
			$this->method = &$_POST;
		
		$this->tableName = $tableName;	
	}
	
	public function genSQL () {
		$tmpFieldName = str_replace(" ", "_", $this->field_name);
		$value = $this->method["narrower_$tmpFieldName"];
		
		if ($value != "" && $value != "0") {
			$reg;
			if (preg_match("/::/", $this->tableName)) {
				$reg = split("::", $this->tableName);
				if ($reg[1] == "r")
					$reg = true;
			} else
				$reg = false;

			if ($reg)
				return " and {$this->tableName} regexp '$value'";
			else
				return " and {$this->tableName} = '$value'";	
		}
	}
	
	
	public function validate () {
		$tmpFieldName = str_replace(" ", "_", $this->field_name);
		$value = $this->method["narrower_$tmpFieldName"];
		
		if (!preg_match("/^[0-9]{0,5}$/", $value)) {
			$this->error = "Please only letter 5 numeric digits.";
			return false;
		} else {
			$this->error = "";
			return true;
		}
	}
	
	
	
	public function genHTML ($type) {
		$html = "";
		
		if ($type == "ajax") {
			
		} else {
			$tmpFieldName = str_replace(" ", "_", $this->field_name);
			$html .= ("Enter number: <input type='text' name='narrower_$tmpFieldName' value='".$this->method["narrower_$tmpFieldName"]."' />");
			$html .= "<br /><div class='narrower_error_message'>{$this->error}</div>";
		}
		
		return $html;
	}
}

class DatesOnly extends TextElement {
	public function __construct ($field_name, $type, $tableName) {
		$this->field_name = $field_name;
		
		
		if ($type == "GET")
			$this->method = &$_GET;
		else if ($type == "POST")
			$this->method = &$_POST;
		
		$this->tableName = $tableName;
		
	}
	
	public function genSQL () {
		$tmpFieldName = str_replace(" ", "_", $this->field_name);
		$value1 = $this->method["narrower_{$tmpFieldName}_entry"];
		$value2 = $this->method["narrower_{$tmpFieldName}_ending"];

		$dateArr1 = explode("/", $value1);
		$dateArr2 = explode("/", $value2);
		$value1 = $dateArr1[2]."-".$dateArr1[0]."-".$dateArr1[1];
		$value2 = $dateArr2[2]."-".$dateArr2[0]."-".$dateArr2[1];
		$sqlString = "";
		
		if ($value1 != "" && $value1 != "0") {
			$sqlString .= " and {$this->tableName} >= '$value1'";	
		}
		
		if ($value2 != "" && $value2 != "0") {
			$sqlString .= " and {$this->tableName} <= '$value2'";
		}

		return $sqlString;

	}
		
	public function validate () {
		$tmpFieldName = str_replace(" ", "_", $this->field_name);
		$value1 = $this->method["narrower_{$tmpFieldName}_entry"];
		$value2 = $this->method["narrower_{$tmpFieldName}_ending"];

		$this->error = "";

		if ($value1 != "") {
			$beginDate = $value1;
			$beginError = "";
			$dateArr = explode("/", $beginDate);

			if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/", $beginDate)) $beginError .= " Please use the proper format for the begin date.";

			if ($beginError == "") { // Still valid
				if ($dateArr[0] < 0 || $dateArr[0] > 12) $beginError .= " The begin date month is not valid.";
				if ($dateArr[1] < 0 || $dateArr[1] > 31) $beginError .= " The begin date day is not valid.";
				if ($dateArr[2] < 2000 || $dateArr[2] > 2500) $beginError .= " The begin date year is not valid."; 
			}

			$beginDate = $dateArr[0]."/".$dateArr[1]."/".$dateArr[2];
			$this->error .= $beginError;
		}


		if ($value2 != "") {
			$endDate = $value2;
			$endError = "";
			$dateArr = explode("/", $endDate);

			if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/", $endDate)) $endError .= " Please use the proper format for the end date.";

			if ($endError == "") { // Still valid
				if ($dateArr[0] < 0 || $dateArr[0] > 12) $endError .= " The end date month is not valid.";
				if ($dateArr[1] < 0 || $dateArr[1] > 31) $endError .= " The end date day is not valid.";
				if ($dateArr[2] < 2000 || $dateArr[2] > 2500) $endError .= " The end date year is not valid."; 
			}

			$endDate = $dateArr[0]."/".$dateArr[1]."/".$dateArr[2];
			$this->error .= $endError;
		}

		if (($value1 != "") && ($value2 != "")) {
			if ($this->error == "") { // The dates are valid
				// XXX: CHECK THIS
				if (strtotime($value1) > strtotime($value2)) {
					$this->error .= " The begin date must be before the end date.";
				}
			}
		}

		if ($this->error == "")
			return true;
		else
			return false;
	}
	public function genHTML ($type) {
		$html = "";
		
		if ($type == "ajax") {
			
		} else {
			$tmpFieldName = str_replace(" ", "_", $this->field_name);			
			$html .= ("Beginning Date (MM/DD/YYYY): <input type='text' id='narrower_{$tmpFieldName}_entry' name='narrower_{$tmpFieldName}_entry"."' value='".$this->method["narrower_{$tmpFieldName}_entry"]."' /><br />Ending Date (MM/DD/YYYY): <input type='text' id='narrower_".$tmpFieldName."_ending' name='narrower_".$tmpFieldName."_ending"."' class='date_end' value='".$this->method["narrower_{$tmpFieldName}_ending"]."' />");
			
			$html .= "<br /><div class='narrower_error_message'>{$this->error}</div>";
		}
		
		return $html;
	}	
}

abstract class DataContainerElement extends FormElement {
	private $data;		// An array of text (mostly)
	
	private $SQL;		// This is provided by the user during initialization
	private $AjaxSQL;	// As is this. The difference in this one is that there are 
				// more limitations imposed on the SQL query since the parent elements
				// would've also changed
				
	
	public function __construct ($field_name, $SQL, $AjaxSQL, $tableName) {
		$this->field_name = $field_name;
		$this->SQL = $SQL;
		$this->AjaxSQL = $AjaxSQL;
		
		$this->tableName = $tableName;
	}
	
	/**
	var type can either be "ajax" or "regular".
	
	This function is called during AJAX mode and during regular creation mode.
	If $type is 'ajax', then this will modify the AjaxSQL given the proper $method 
	parameters. After modifying AjaxSQL (or simply using SQL), this will pass in the
	new query to populate

	This is still abstract since the data container can be anything...
	Mostly, we will use drop down lists though
	*/
	public function genHTML($type) {
	}
	
	/**
	This is the master function for data container elements. This is called from
	genHTML($type). Basically, it will run the SQL provided from genHTML
	*/
	private function populate ($sql) {
		
	}
}


class DropDownMenu extends DataContainerElement {
	
	public function __construct ($field_name, $SQL, $AjaxSQL, $type, $tableName) {
		$this->field_name = $field_name;
		$this->SQL = $SQL;
		$this->AjaxSQL = $AjaxSQL;
		
		if ($type == "GET")
			$this->method = &$_GET;
		else if ($type == "POST")
			$this->method = &$_POST;
		
		$this->tableName = $tableName;
		
	}
	
	public function genSQL () {
		$tmpFieldName = str_replace(" ", "_", $this->field_name);
		$value = $this->method["narrower_$tmpFieldName"];
		
		if ($value != "" && $value != "0") {
			$reg;
			if (preg_match("/::/", $this->tableName)) {
				$reg = 	split("::", $this->tableName);
				if ($reg[1] == "r")
					$reg = true;
			} else
				$reg = false;

			if ($reg)
				return " and {$this->tableName} regexp '$value'";
			else
				return " and {$this->tableName} = '$value'";	
		}
	}	
	
	public function validate() {
		return true;
	}
	public function genHTML ($type) {
		$html = "";
		
		$all0 = true;
		if ($type == "ajax") {
			foreach ($this->parents as $parent) {
				if ($all0) {	// innocent until proven guilty
					$tmpName = str_replace(" ", "_", $parent);
					if ($this->method["narrower_$tmpName"] != 0)
						$all0 = false;
				}
			}
		}
		
		if ($type == "ajax" && !$all0) {
			db_connect();
			$tmpFieldName = str_replace(" ", "_", $this->field_name);
			
			
			if (count($this->children) > 0) {
				$functionName = str_replace(" ", "_", $this->field_name);
				$functionName = "narrower_ajax_$functionName();";
			
				$html .= "<select name='narrower_$tmpFieldName' onchange='$functionName'>\n";
			} else {
				$html .= "<select name='narrower_$tmpFieldName'>\n";				
			}
			
			$html .= "<option value='0'>Select all</option>\n";
			
			$tmpSQL = $this->AjaxSQL;
			
			$itemNum = 0;
			foreach ($this->parents as $parent) {
				$parentName = $this->parents[$itemNum];
				$parentName = str_replace(" ", "_", $parentName);
				if ($this->method["narrower_$parentName"] == 0) {
					$pattern = " and 'param$itemNum'='param$itemNum' and .*='XXX$itemNum'";
					$tmpSQL = ereg_replace($pattern, "",$tmpSQL);
					//echo (" FOUND IT FOR $parentName REMOVING USING $pattern");
				} else {
					$tmpSQL = str_replace("XXX$itemNum", $this->method["narrower_$parentName"], $tmpSQL);
				}
				
				$itemNum += 1;
			}
			
			if ($result = mysql_query($tmpSQL)) {
				while ($row = mysql_fetch_array($result)) {
					$html .= "<option value='{$row[0]}'>{$row[1]}</option>\n";
				}
			}
			$html .= "</select>\n";
			$html .= "<br /><div class='narrower_error_message'>{$this->error}</div>";

		} else {
			db_connect();
			
			$tmpFieldName = str_replace(" ", "_", $this->field_name);

			if (count($this->children) > 0) {
				$functionName = str_replace(" ", "_", $this->field_name);
				$functionName = "narrower_ajax_$functionName();";
			

				$html .= "<select name='narrower_$tmpFieldName' onchange='$functionName'>\n";
			} else {
				$html .= "<select name='narrower_$tmpFieldName'>\n";				
			}
			$html .= "<option value='0'>Select all</option>\n";
			if ($result = mysql_query($this->SQL)) {
				while ($row = mysql_fetch_array($result)) {
					$selected = "";
					if ($this->method["narrower_$tmpFieldName"] == $row[0])
						$selected = " selected=selected";
					
					$html .= "<option value='{$row[0]}'$selected>{$row[1]}</option>\n";
				}
			}
			$html .= "</select>\n";
			$html .= "<br /><div class='narrower_error_message'>{$this->error}</div>";
		}		
		
		return $html;
	}
	
}

class CommaDropDown extends DataContainerElement {
	// STILL NEED TO IMPLEMENT MULTI PARENTS FOR COMMAS... AVOIDED IT DUE TO LAZINESS
	
	public function __construct ($field_name, $SQL, $AjaxSQL, $type, $tableName) {
		$this->field_name = $field_name;
		$this->SQL = $SQL;
		$this->AjaxSQL = $AjaxSQL;

		if ($type == "GET")
			$this->method = &$_GET;
		else if ($type == "POST")
			$this->method = &$_POST;
			
			
		$this->tableName = $tableName;
	}
	
	public function genSQL () {
		$tmpFieldName = str_replace(" ", "_", $this->field_name);
		$value = $this->method["narrower_$tmpFieldName"];
		
		if ($value != "" && $value != "0") {
			$reg;
			if (preg_match("/::/", $this->tableName)) {
				$reg = split("::", $this->tableName);
				if ($reg[1] == "r")
					$reg = true;
			} else
				$reg = false;

			if ($reg)
				return " and {$this->tableName} regexp '$value'";
			else
				return " and {$this->tableName} = '$value'";	
		}
	}	

	public function validate() {
		return true;
	}
	public function genHTML ($type) {
		$html = "";
		
		if ($type == "ajax") {
			$html .= "<select name='narrower_{$this->field_name}'>\n";
			$html .= "<option value='0'>Select all</option>\n";
			
			db_connect();
			
			
			$firstSQL = explode("|", $this->AjaxSQL);
			$secondSQL = $firstSQL[1];
			$firstSQL = $firstSQL[0];


			$tmpSQL = $firstSQL;
			$parentName = $this->parents[0];
			$parentName = str_replace(" ", "_", $parentName);
			$tmpSQL = str_replace("XXX0", $this->method["narrower_$parentName"], $tmpSQL);


			$values = array();
			if ($result = mysql_query($tmpSQL)) {
				$row = mysql_fetch_array($result);
				$values = explode(",", $row[0]);
			}
			
			
			foreach ($values as $value) {
				$secondSQL = str_replace("XXX", "".$value, $secondSQL);
				if ($result = mysql_query($secondSQL)) {
					$row = mysql_fetch_array($result);
					$html .= "<option value='{$value}'>{$row[0]}</option>\n";
				}
			}
			$html .= "</select>\n";			
			$html .= "<br /><div class='narrower_error_message'>{$this->error}</div>";

		} else {
			
			$html .= "<select name='narrower_{$this->field_name}'>\n";
			$html .= "<option value='0'>Select all</option>\n";
			
			$tmpFieldName = str_replace(" ", "_", $this->field_name);
			
			db_connect();
			$firstSQL = explode("|", $this->SQL);
			$secondSQL = $firstSQL[1];
			$firstSQL = $firstSQL[0];

			$values = array();
			if ($result = mysql_query($firstSQL)) {
				$row = mysql_fetch_array($result);
				$values = explode(",", $row[0]);
			}
			
			
			foreach ($values as $value) {
				$secondSQL = str_replace("XXX", "".$value, $secondSQL);
				if ($result = mysql_query($secondSQL)) {
					$row = mysql_fetch_array($result);
					$selected = "";
					if ($this->method["narrower_$tmpFieldName"] == $value)
						$selected = " selected=selected";
					
					$html .= "<option value='{$value}'$selected>{$row[0]}</option>\n";
				}
			}
			$html .= "</select>\n";
			$html .= "<br /><div class='narrower_error_message'>{$this->error}</div>";

		}
		
		return $html;
	}
}



/**
The difference between this class and CommaDropDown class is that in this class, the initialization is as if it it was a normal drop down object. 
The AJAX population is still comma separated... for the most part.

Children not at all supported for commadropdown AND for commadropdownfusion

*/
class CommaDropDownFusion extends DataContainerElement {
	// STILL NEED TO IMPLEMENT MULTI PARENTS FOR COMMAS... AVOIDED IT DUE TO LAZINESS

	public function __construct ($field_name, $SQL, $AjaxSQL, $type, $tableName) {
		$this->field_name = $field_name;
		$this->SQL = $SQL;
		$this->AjaxSQL = $AjaxSQL;

		if ($type == "GET")
			$this->method = &$_GET;
		else if ($type == "POST")
			$this->method = &$_POST;

		$this->tableName = $tableName;
	}
	
	public function genSQL () {
		$tmpFieldName = str_replace(" ", "_", $this->field_name);
		$value = $this->method["narrower_$tmpFieldName"];

		if ($value != "" && $value != "0") {
			$reg;
			if (preg_match("/::/", $this->tableName)) {
				$reg = split("::", $this->tableName);
				if ($reg[1] == "r")
					$reg = true;
			} else
				$reg = false;

			if ($reg)
				return " and {$this->tableName} regexp '$value'";
			else
				return " and {$this->tableName} = '$value'";	
		}
	}	

	public function validate() {
		return true;
	}
	
	public function genHTML ($type) {
		$html = "";
		
		if ($type == "ajax") {
			$html .= "<select name='narrower_{$this->field_name}'>\n";
			$html .= "<option value='0'>Select all</option>\n";
			
			db_connect();
			
			
			$firstSQL = explode("|", $this->AjaxSQL);
			$secondSQL = $firstSQL[1];
			$firstSQL = $firstSQL[0];


			$tmpSQL = $firstSQL;
			$parentName = $this->parents[0];
			$parentName = str_replace(" ", "_", $parentName);
			$tmpSQL = str_replace("XXX0", $this->method["narrower_$parentName"], $tmpSQL);


			$values = array();
			if ($result = mysql_query($tmpSQL)) {
				$row = mysql_fetch_array($result);
				$values = explode(",", $row[0]);
			}
			
			
			foreach ($values as $value) {
				$secondSQL = str_replace("XXX", "".$value, $secondSQL);
				if ($result = mysql_query($secondSQL)) {
					$row = mysql_fetch_array($result);
					$html .= "<option value='{$value}'>{$row[0]}</option>\n";
				}
			}
			$html .= "</select>\n";			
			$html .= "<br /><div class='narrower_error_message'>{$this->error}</div>";

		} else {
			db_connect();
			
			$tmpFieldName = str_replace(" ", "_", $this->field_name);

			if (count($this->children) > 0) {
				$functionName = str_replace(" ", "_", $this->field_name);
				$functionName = "narrower_ajax_$functionName();";
			

				$html .= "<select name='narrower_$tmpFieldName' onchange='$functionName'>\n";
			} else {
				$html .= "<select name='narrower_$tmpFieldName'>\n";				
			}
			$html .= "<option value='0'>Select all</option>\n";
			if ($result = mysql_query($this->SQL)) {
				while ($row = mysql_fetch_array($result)) {
					$selected = "";
					if ($this->method["narrower_$tmpFieldName"] == $row[0])
						$selected = " selected=selected";
					
					$html .= "<option value='{$row[0]}'$selected>{$row[1]}</option>\n";
				}
			}
			$html .= "</select>\n";
			$html .= "<br /><div class='narrower_error_message'>{$this->error}</div>";
		}
		
		return $html;
	}
}

?>